<template>
  <el-dropdown placement="bottom" trigger="click" popper-class="el-tiptap-dropdown-popper" @command="toggleHeading"
    :popper-options="{ modifiers: [{ name: 'computeStyles', options: { adaptive: false } }] }">
    <div class="ai-button">
      <command-button :enable-tooltip="false" :is-active="editor.isActive('ai')"
        tooltip="人工智能" :readonly="isCodeViewMode" :button-icon="buttonIcon"
        icon="ai" />
        <!-- <Wand color="#d60a15"/> -->
    </div>
    <template #dropdown>
      <el-dropdown-menu class="el-tiptap-dropdown-menu">
        <el-dropdown-item @click="aiGenate2">
          <div class="el-tiptap-dropdown-item"> 生成一篇文章 </div>
        </el-dropdown-item>
        <el-dropdown-item @click="transEnglish">
          <div class="el-tiptap-dropdown-item"> 翻译 </div>
        </el-dropdown-item>
        <el-dropdown-item>
          <div class="el-tiptap-dropdown-item"> 生成语音 </div>
        </el-dropdown-item>
      </el-dropdown-menu>
    </template>
  </el-dropdown>
</template>

<script  setup>
import { defineComponent, inject, ref } from 'vue';
import { ElDropdown, ElDropdownMenu, ElDropdownItem } from 'element-plus';
import { Editor } from '@tiptap/core';
import CommandButton from './CommandButton.vue';
import TypeIt from 'typeit'
import { trans2English, chat } from '@/api/plugin'
import { Wand } from 'lucide-vue-next';

const props = defineProps({
  editor: {
    type: Editor,
    required: true,
  },
  buttonIcon: {
    default: '',
    type: String
  }
},)


const t = inject('t');
const enableTooltip = inject('enableTooltip', true);
const isCodeViewMode = inject('isCodeViewMode', false);

function toggleHeading(level) {
  if (level > 0) {
    props.editor.commands.toggleHeading({ level });
  } else {
    props.editor.commands.setParagraph();
  }
}

function getSelection() {
  const { from, to } = props.editor.view.state.selection
  // console.log(props.editor.view.state.doc.textBetween(from, to, ' '));
  return props.editor.view.state.doc.textBetween(from, to, ' ')
}
function aiGenate() {
  console.log(getSelection());
  const len = document.querySelectorAll('p').length
  // https://www.typeitjs.com/docs/vanilla/usage/ 打字机效果
  new TypeIt(document.querySelectorAll('p')[len - 1], {
    strings: ['This is a greata greata', ' greata greata greata ', 'greatBut here ', 'is a better one. ', 'This is a ', 'greata greata gre', 'ata greata greata', ' greatBut her', 'e is a better one.'],
    speed: 1,
    nextStringDelay: [0, 10],
    cursorChar: '',
    waitUntilVisible: false,
    beforeString: (characters, instance) => {
      props.editor.commands.insertContent(characters)
    }
  }).go();
}

function aiGenate2() {
  console.log(getSelection());
  const len = document.querySelectorAll('p').length
  const prompt = getSelection()
  // props.editor.commands.insertContent(`${prompt}\n`)
  chat(prompt).then(async(reader) =>{
    const textDecoder = new TextDecoder();
    let result = true;
    let output = "";
    while (result) {
      const { done, value } = await reader.read();

      if (done) {
        console.log("Stream ended");
        result = false;
        break;
      }
      const chunkText = textDecoder.decode(value);

      props.editor.commands.insertContent(chunkText.replace(/\n/g, '<br>').replace(/\r/g, '<br>').replace(/\s/g, ' '))
      // output += chunkText;
      // console.log("Received chunk:", chunkText);
    }
  })

}

function transEnglish() {
  // console.log('-------------');
  let text = getSelection();
  if (text?.length > 0) {
    // console.log('----------------');
  } else {
    text = props.editor.getText();
  }
  trans2English(text).then((result) => {
    console.log(result.data.result);
    props.editor.commands.deleteSelection()
    props.editor.commands.insertContent(result.data.result)

  })

  // console.log(text);
  // console.log(props.editor.getText())
}




</script>

<style scoped>
.ai-dropdown {
  line-height: 45px;
  height: 45px;
}

.el-tiptap-dropdown-item {
  /* width: 100px; */
  font-size: 16px;
  padding: 5px 10px;
}


.msg {
  color: rgb(88, 88, 88);
  letter-spacing: 2px;
}

.msg ::v-deep .cursorChar {
  display: inline-block;
  margin-left: 2px;
}
</style>
